package com.sk.weichat.ui.account;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hlg.yueliao.wxapi.WXEntryActivity;
import com.hlg.yueliao.wxapi.WXHelper;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.adapter.MessageLogin;
import com.sk.weichat.bean.LoginRegisterResult;
import com.sk.weichat.bean.WXUploadResult;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.helper.PasswordHelper;
import com.sk.weichat.helper.PrivacySettingHelper;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.WebAgreementActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.EventBusHelper;
import com.sk.weichat.util.Md5Util;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectionFrame;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

import static com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_NO_PASSWORD;
import static com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_SUCCESS;

/**
 * 登录界面
 *
 * @author Dean Tao
 * @version 1.0
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private AutoCompleteTextView mPhoneNumberEdit;
    private AutoCompleteTextView mPasswordEdit;
    private TextView tv_prefix, tvUserAgreement, tvPrivacyPolicy;
    private int mobilePrefix = 86;
    private String thirdToken;
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
    private Button forgetPasswordBtn, registerBtn, loginBtn, btnVerifyCodeLogin;
    private ImageView ivClear, ivClearPsw, ivWXLogin, ivQQLogin;
    private BaseUiListener mIUiListener;
    private Tencent mTencent;
    private int mOldLoginStatus;

    public LoginActivity() {
        noLoginRequired();
    }

    public static void bindThird(Context ctx, WXUploadResult thirdToken) {
        Intent intent = new Intent(ctx, LoginActivity.class);
        intent.putExtra("thirdToken", JSON.toJSONString(thirdToken));
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//暗色主题状态栏(白字)
            this.getWindow().getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_VISIBLE);
        }
        setContentView(R.layout.activity_login);

        //腾讯QQ登录初始化
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APP_ID, this.getApplicationContext());
        }
        mOldLoginStatus = MyApplication.getInstance().mUserStatus;
        thirdToken = getIntent().getStringExtra("thirdToken");
        initActionBar();
        initView();

        IntentFilter filter = new IntentFilter();
        filter.addAction("CHANGE_CONFIG");
        registerReceiver(broadcastReceiver, filter);

        if (!TextUtils.isEmpty(thirdToken)) {
            // 第三方进来直接登录，
            // 清空手机号以标记是第三方登录，
            mPhoneNumberEdit.setText("");
            login(true);
        }
        EventBusHelper.register(this);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(MessageLogin message) {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 如果没有保存用户定位信息，那么去地位用户当前位置
        if (!MyApplication.getInstance().getBdLocationHelper().isLocationUpdate()) {
            MyApplication.getInstance().getBdLocationHelper().requestLocation();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(Color.parseColor("#00000000"));

        ImageView ivBack = findViewById(R.id.iv_title_left);
        ivBack.setImageResource(R.mipmap.ic_back_white);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSmsLogin();
            }
        });
//        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
//        if (TextUtils.isEmpty(thirdToken)) {
//            tvTitle.setText(getString(R.string.login));
//        } else {
//            // 第三方登录的不要提示登录，而是绑定手机号码，
//            tvTitle.setText(getString(R.string.bind_phone_number));
//        }

//        TextView tvRight = (TextView) findViewById(R.id.tv_title_right);
//        // 定制包隐藏设置服务器按钮，
//        if (!AppConfig.isShiku()) {
//            // 为方便测试，留个启用方法，adb shell命令运行"setprop log.tag.ShikuServer D"启用，
//            if (!Log.isLoggable("ShikuServer", Log.DEBUG)) {
//                tvRight.setVisibility(View.GONE);
//            }
//        }
//        tvRight.setText(R.string.settings_server_address);
//        tvRight.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(LoginActivity.this, SetConfigActivity.class);
//                startActivity(intent);
//            }
//        });
    }

    private void initView() {
        mPhoneNumberEdit = findViewById(R.id.phone_number_edit);
        String phoneGet = getIntent().getStringExtra("phoneNum");
        if (!TextUtils.isEmpty(phoneGet)) {
            mPhoneNumberEdit.setText(phoneGet);
            mPhoneNumberEdit.setSelection(phoneGet.length());
        }
        mPasswordEdit = findViewById(R.id.password_edit);
        PasswordHelper.bindPasswordEye(mPasswordEdit, findViewById(R.id.tbEye));
        tv_prefix = (TextView) findViewById(R.id.tv_prefix);
        if (coreManager.getConfig().registerUsername) {
            tv_prefix.setVisibility(View.GONE);
        } else {
            tv_prefix.setOnClickListener(this);
        }
        mobilePrefix = PreferenceUtils.getInt(this, Constants.AREA_CODE_KEY, mobilePrefix);
        tv_prefix.setText("+" + mobilePrefix);

        // 登录账号
        loginBtn = (Button) findViewById(R.id.login_btn);
        // loginBtn.setBackgroundColor(SkinUtils.getSkin(this).getAccentColor());
        loginBtn.setOnClickListener(this);
        // 注册账号
        registerBtn = (Button) findViewById(R.id.register_account_btn);
//        if (TextUtils.isEmpty(thirdToken)) {
//            registerBtn.setOnClickListener(this);
//        } else {
//            // 第三方登录的不需要这个注册按钮，登录后没有账号直接跳到注册，
//            registerBtn.setVisibility(View.GONE);
//        }
//        if (coreManager.getConfig().isOpenRegister) {
//            registerBtn.setVisibility(View.VISIBLE);
//        } else {
//            registerBtn.setVisibility(View.GONE);
//        }
        // 忘记密码
        forgetPasswordBtn = (Button) findViewById(R.id.forget_password_btn);
        if (coreManager.getConfig().registerUsername) {
            forgetPasswordBtn.setVisibility(View.GONE);
        }
/*
        forgetPasswordBtn.setTextColor(SkinUtils.getSkin(this).getAccentColor());
*/
        forgetPasswordBtn.setOnClickListener(this);
//        UsernameHelper.initEditText(mPhoneNumberEdit, coreManager.getConfig().registerUsername);
        // mPasswordEdit.setHint(InternationalizationHelper.getString("JX_InputPassWord"));
        loginBtn.setText(InternationalizationHelper.getString("JX_Login"));
        registerBtn.setText(InternationalizationHelper.getString("JX_Register"));
        forgetPasswordBtn.setText(InternationalizationHelper.getString("JX_ForgetPassWord"));

        findViewById(R.id.sms_login_btn).setOnClickListener(this);

        if (TextUtils.isEmpty(thirdToken)) {
            findViewById(R.id.wx_login_btn).setOnClickListener(this);
        } else {
            findViewById(R.id.wx_login_fl).setVisibility(View.GONE);
        }

        findViewById(R.id.main_content).setOnClickListener(this);

        if (!coreManager.getConfig().thirdLogin) {
            findViewById(R.id.wx_login_fl).setVisibility(View.GONE);
        }

        if (coreManager.getConfig().registerUsername) {
            // 开启用户名注册登录的情况隐藏短信登录，
            findViewById(R.id.sms_login_fl).setVisibility(View.GONE);
        }
        ivClear = findViewById(R.id.iv_clear_num);
        ivClear.setOnClickListener(this);
        ivClearPsw = findViewById(R.id.iv_clear_psw);
        ivClearPsw.setOnClickListener(this);
        btnVerifyCodeLogin = findViewById(R.id.btn_verify_code_login);
        btnVerifyCodeLogin.setOnClickListener(this);
        tvUserAgreement = findViewById(R.id.tv_user_agreement);
        tvUserAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToWeb("悦聊用户协议", coreManager.getConfig().GET_USER_AGREEMENT);
            }
        });
        tvPrivacyPolicy = findViewById(R.id.tv_privacy_policy);
        tvPrivacyPolicy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToWeb("悦聊隐私政策", coreManager.getConfig().GET_POLICY);
            }
        });
        ivWXLogin = findViewById(R.id.iv_wei_xin_login);
        ivWXLogin.setOnClickListener(this);
        ivQQLogin = findViewById(R.id.iv_qq_login);
        ivQQLogin.setOnClickListener(this);
        chinaNumInput();
        pswInputEvent();
    }

    //密码输入监听事件
    private void pswInputEvent() {
        mPasswordEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && !TextUtils.isEmpty(mPasswordEdit.getText())) {
                    ivClearPsw.setVisibility(View.VISIBLE);
                } else {
                    ivClearPsw.setVisibility(View.GONE);
                }
            }
        });
        mPasswordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    ivClearPsw.setVisibility(View.INVISIBLE);
                    return;
                }
                ivClearPsw.setVisibility(View.VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_prefix:
                // 选择国家区号
                Intent intent = new Intent(this, SelectPrefixActivity.class);
                startActivityForResult(intent, SelectPrefixActivity.REQUEST_MOBILE_PREFIX_LOGIN);
                break;
            case R.id.login_btn:
                // 登录
                login(false);
                break;
            case R.id.wx_login_btn:
                WXEntryActivity.wxLogin(this);
                break;
            case R.id.register_account_btn:
                // 注册
                register();
                break;
            case R.id.forget_password_btn:
                // 忘记密码
//                Intent intent0 = new Intent(LoginActivity.this, SMSForgetPswActivity.class);
//                intent0.putExtra("phoneNum", mPhoneNumberEdit.getText().toString());
                startActivity(new Intent(LoginActivity.this, SMSForgetPswActivity.class));
                break;
            case R.id.sms_login_btn:
                Intent iS = new Intent(LoginActivity.this, SwitchLoginActivity.class);
                iS.putExtra("thirdTokenLogin", thirdToken);
                startActivity(iS);
                finish();
                break;
            case R.id.main_content:
                // 点击空白区域隐藏软键盘
                InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (inputManager != null) {
                    inputManager.hideSoftInputFromWindow(findViewById(R.id.main_content).getWindowToken(), 0); //强制隐藏键盘
                }
                break;
            case R.id.iv_clear_num:
                mPhoneNumberEdit.setText("");
                break;
            case R.id.iv_clear_psw:
                mPasswordEdit.setText("");
                break;
            case R.id.btn_verify_code_login:
                startSmsLogin();
                break;
            case R.id.iv_wei_xin_login://微信登录
                WXEntryActivity.wxLogin(this);
                break;
            case R.id.iv_qq_login://QQ登录
                mIUiListener = new BaseUiListener();
                //all表示获取所有权限
                mTencent.login(LoginActivity.this, "all", mIUiListener);
                break;
        }
    }

    private void register() {
        RegisterActivity.registerFromThird(
                this,
                mobilePrefix,
                mPhoneNumberEdit.getText().toString().replace(" ", ""),
                mPasswordEdit.getText().toString()
                , thirdToken
        );
    }

    //启动验证码登录界面
    private void startSmsLogin() {
        Intent intent1 = new Intent(LoginActivity.this, SMSLoginActivity.class);
        intent1.putExtra("thirdTokenLogin", thirdToken);
//        intent1.putExtra("phoneNum", mPhoneNumberEdit.getText().toString());
        startActivity(intent1);
        overridePendingTransition(R.anim.back_anim_show, R.anim.back_anim_out);
        finish();
    }

    /**
     * @param third 第三方自动登录，
     */
    private void login(boolean third) {
        PreferenceUtils.putInt(this, Constants.AREA_CODE_KEY, mobilePrefix);
        final String phoneNumber = mPhoneNumberEdit.getText().toString().replace(" ", "");
        String password = mPasswordEdit.getText().toString().trim();

        if (TextUtils.isEmpty(thirdToken)) {
            // 第三方登录的不处理账号密码，
            if (TextUtils.isEmpty(phoneNumber) && TextUtils.isEmpty(password)) {
                Toast.makeText(mContext, getString(R.string.please_input_account_and_password), Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(phoneNumber)) {
                Toast.makeText(mContext, getString(R.string.please_input_account), Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(mContext, InternationalizationHelper.getString("JX_InputPassWord"), Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (!StringUtils.checkPassword(password)) {
            ToastUtil.showToast(mContext, getString(R.string.password_confirm_password_type));
            return;
        }
        // 加密之后的密码
        final String digestPwd = Md5Util.toMD5(password);
        // 加密后的手机号码
        String digestPhoneNumber = Md5Util.toMD5(phoneNumber);

        DialogHelper.showDefaulteMessageProgressDialog(this);

        Map<String, String> params = new HashMap<>();
        params.put("telephone", digestPhoneNumber);          // 账号登录的时候需要MD5加密，服务器需求
        params.put("password", digestPwd);
        params.put("xmppVersion", "1");
        // 附加信息+
        params.put("model", DeviceInfoUtil.getModel());
        params.put("osVersion", DeviceInfoUtil.getOsVersion());
        params.put("serial", DeviceInfoUtil.getDeviceId(mContext));
        // 地址信息
        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        if (latitude != 0)
            params.put("latitude", String.valueOf(latitude));
        if (longitude != 0)
            params.put("longitude", String.valueOf(longitude));

        if (MyApplication.IS_OPEN_CLUSTER) {// 服务端集群需要
            String area = PreferenceUtils.getString(this, AppConstant.EXTRA_CLUSTER_AREA);
            if (!TextUtils.isEmpty(area)) {
                params.put("area", area);
            }
        }

        String url;
        if (TextUtils.isEmpty(thirdToken)) {
            url = coreManager.getConfig().USER_LOGIN;
        } else {
            params.put("type", "2");
            params.put("loginInfo", WXHelper.parseOpenId(thirdToken));
            if (third) {
                // 第三方自动登录，
                // 先尝试直接用这个微信登录，
                // 如果返回1040305表示这个微信没有绑定IM账号，
                // 留在这个登录页面等待用户输入账号密码，
                url = coreManager.getConfig().USER_THIRD_LOGIN;
            } else {
                // 用户输入IM账号密码后将该IM账号与微信绑定，
                // 如果返回1040306表示这个IM账号不存在，跳到注册页面让用户走注册IM账号并绑定微信，
                url = coreManager.getConfig().USER_THIRD_BIND;
                // 账号绑定的时候不需要MD5加密，并拼接区号，
                params.put("telephone", mobilePrefix + phoneNumber);
            }
        }
        HttpUtils.get().url(url)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {

                    @Override
                    public void onResponse(com.xuan.xuanhttplibrary.okhttp.result.ObjectResult<LoginRegisterResult> result) {
                        DialogHelper.dismissProgressDialog();
                        boolean legal = result != null && result.getResultCode() == CODE_SUCCESS;
                        if (!legal) {
                            String tips;
                            if (result.getResultMsg().equals("账号不存在，请通过验证码登录!")
                                    && result.getResultCode() == 0) {
                                tips = result.getResultMsg();
                            } else if (result.getResultCode() == CODE_NO_PASSWORD) {//未设置密码
                                tips = result.getResultMsg();
                            } else {
                                ToastUtil.showToast(mContext, result.getResultMsg());
                                return;
                            }

                            SelectionFrame mSF = new SelectionFrame(mContext);
                            mSF.setSomething("温馨提示", tips, new SelectionFrame.OnSelectionFrameClickListener() {
                                @Override
                                public void cancelClick() {

                                }

                                @Override
                                public void confirmClick() {
                                    startSmsLogin();
                                }
                            });
                            mSF.show();

                          /*  TipDialog tipDialog = new TipDialog(mContext);
                            tipDialog.setmConfirmOnClickListener(tips, new TipDialog.ConfirmOnClickListener() {
                                @Override
                                public void confirm() {
                                    startSmsLogin();
                                }
                            });
                            tipDialog.show();*/
                            return;
                        }
                        if (result.getData().getIsRegister() == 1) {
                            boolean success = LoginHelper.setLoginUser(mContext, coreManager, phoneNumber, digestPwd, result);
                            if (success) {
                                //判断是否是添加多账号
                                MultiAccountHelper.onLoginSuccess(mContext, result.getData().getUserId());
                                PreferenceUtils.putBoolean(LoginActivity.this, Constants.LOGIN_CONFLICT, false);// 重置登录冲突记录
                                LoginRegisterResult.Settings settings = result.getData().getSettings();
                                MyApplication.getInstance().initPayPassword(result.getData().getUserId(), result.getData().getPayPassword());
                                PrivacySettingHelper.setPrivacySettings(LoginActivity.this, settings);
                                startActivity(new Intent(mContext, DataDownloadActivity.class));
                                finish();
                            } else { //  登录出错 || 用户资料不全
                                String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.tip_incomplete_information) : result.getResultMsg();
                                ToastUtil.showToast(mContext, message);
                            }
                        } else {
                            Intent intent = new Intent(getApplicationContext(), RegisterUserBasicInfoActivity.class);
                            intent.putExtra(RegisterActivity.EXTRA_AUTH_CODE, "" + result.getData().getAreaCode());
                            intent.putExtra(RegisterActivity.EXTRA_PHONE_NUMBER, result.getData().getTelephone());
                            intent.putExtra(RegisterActivity.EXTRA_INVITE_CODE, "");
                            intent.putExtra(RegisterActivity.EXTRA_PASSWORD, "");

                            //微信
                            if (result.getData().getWxUser() != null) {
                                if (!TextUtils.isEmpty(result.getData().getWxUser().getNickName())) {
                                    intent.putExtra("nickname", result.getData().getWxUser().getNickName());
                                    intent.putExtra("sex", result.getData().getWxUser().getSex());
                                    intent.putExtra("imgurl", result.getData().getWxUser().getImgurl());
                                    intent.putExtra("thirdToken", "");
                                }
                            }

                            //QQ
                            if (result.getData().getQqUser() != null) {
                                if (!TextUtils.isEmpty(result.getData().getQqUser().getNickName())) {
                                    intent.putExtra("nickname", result.getData().getQqUser().getNickName());
                                    intent.putExtra("sex", result.getData().getQqUser().getSex());
                                    intent.putExtra("imgurl", result.getData().getQqUser().getImgurl());
                                    intent.putExtra("thirdToken", "");
                                }
                            }
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_LOGIN ||
                requestCode == com.tencent.connect.common.Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
            return;
        }
        if (resultCode != SelectPrefixActivity.RESULT_MOBILE_PREFIX_SUCCESS)
            return;
        mobilePrefix = data.getIntExtra(Constants.MOBILE_PREFIX, 86);
        tv_prefix.setText("+" + mobilePrefix);
        mPhoneNumberEdit.setText("");
    }

    //输入号码格式校验
    private void chinaNumInput() {
        String inputStr = mPhoneNumberEdit.getText().toString();
        if (TextUtils.isEmpty(inputStr)) {
            ivClear.setVisibility(View.INVISIBLE);
            loginBtn.setTextColor(mContext.getResources().getColor(R.color.white));
            loginBtn.setBackgroundResource(R.drawable.bg_round_white_35);
        } else {
            ivClear.setVisibility(View.VISIBLE);
            loginBtn.setTextColor(mContext.getResources().getColor(R.color.deep_purple));
            loginBtn.setBackgroundResource(R.drawable.bg_round_white);
        }
        mPhoneNumberEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus && !TextUtils.isEmpty(mPhoneNumberEdit.getText())) {
                ivClear.setVisibility(View.VISIBLE);
            } else {
                ivClear.setVisibility(View.GONE);
            }
        });
        mPhoneNumberEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    ivClear.setVisibility(View.INVISIBLE);
                    loginBtn.setTextColor(mContext.getResources().getColor(R.color.white));
                    loginBtn.setBackgroundResource(R.drawable.bg_round_white_35);
                    return;
                }
                ivClear.setVisibility(View.VISIBLE);
                loginBtn.setTextColor(mContext.getResources().getColor(R.color.deep_purple));
                loginBtn.setBackgroundResource(R.drawable.bg_round_white);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * QQ登录授权回调
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                ToastUtil.showToast(LoginActivity.this, "登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                ToastUtil.showToast(LoginActivity.this, "登录失败");
                return;
            }
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject obj) {

            try {
                DialogHelper.showMessageProgressDialog(LoginActivity.this, "正在登录...");
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken, expires);
                QQToken qqToken = mTencent.getQQToken();
                UserInfo mUserInfo = new UserInfo(getApplicationContext(), qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        //是一个json串response.tostring，直接使用gson解析就好
                        Log.e(TAG, "登录成功" + response.toString());
                        loginQQ(openID, response);

                    }

                    @Override
                    public void onError(UiError uiError) {
                        DialogHelper.dismissProgressDialog();
                        Log.e(TAG, "登录失败" + uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        DialogHelper.dismissProgressDialog();
                        Log.e(TAG, "登录取消");

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError e) {
            DialogHelper.dismissProgressDialog();
            ToastUtil.showToast(LoginActivity.this, "登录失败");
        }

        @Override
        public void onCancel() {
            DialogHelper.dismissProgressDialog();
            ToastUtil.showToast(LoginActivity.this, "登录取消");
        }
    }

    /**
     * QQ授权后请求服务器登录
     *
     * @param code     QQ授权返回的openId
     * @param response QQ登录返回的用户信息
     */
    private void loginQQ(String code, Object response) {

        JSONObject JSONResponse = (JSONObject) response;
        Map<String, String> params = new HashMap<>();
        params.put("loginInfo", code);
        params.put("type", Constants.LOGIN_QQ);
        params.put("nickname", JSONResponse.optString("nickname"));
        params.put("sex", JSONResponse.optString("gender").equals("男") ? "1" : "0");
        params.put("imgurl", JSONResponse.optString("figureurl_qq_1"));
        params.put("province", JSONResponse.optString("province"));
        params.put("city", JSONResponse.optString("city"));
        params.put("serial", DeviceInfoUtil.getDeviceId(mContext));
        params.put("model", DeviceInfoUtil.getModel());
        params.put("latitude", String.valueOf(MyApplication.getInstance().getBdLocationHelper().getLatitude()));
        params.put("longitude", String.valueOf(MyApplication.getInstance().getBdLocationHelper().getLongitude()));

        HttpUtils.get().url(coreManager.getConfig().THIRD_GET_LOGING)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {

                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (Result.checkSuccess(getApplicationContext(), result)) {
                            Intent intent;
                            switch (result.getData().getStatus()) {

                                case 0: //0,未绑定手机号；
                                    intent = new Intent(getApplicationContext(), BandAndChangePhoneActivity.class);
                                    intent.putExtra("type", Constants.BAND_PHONE_QQ);
                                    intent.putExtra("loginType", Constants.LOGIN_QQ);
                                    intent.putExtra("openId", result.getData().getOpenId());
                                    intent.putExtra("nickname", result.getData().getNickName());
                                    intent.putExtra("sex", result.getData().getSex());
                                    intent.putExtra("imgurl", result.getData().getHeadImgUrl());
                                    startActivity(intent);
                                    break;

                                case 1://1，成功登录
                                    loginQQSuccess(result);
                                    break;

                                case 2://2,未完善个人信息；
                                    intent = new Intent(getApplicationContext(), RegisterUserBasicInfoActivity.class);
                                    intent.putExtra(RegisterActivity.EXTRA_AUTH_CODE, result.getData().getAreaCode());
                                    intent.putExtra(RegisterActivity.EXTRA_PHONE_NUMBER, result.getData().getTelephone());
                                    intent.putExtra(RegisterActivity.EXTRA_INVITE_CODE, "");
                                    intent.putExtra(RegisterActivity.EXTRA_PASSWORD, "");
                                    intent.putExtra("nickname", result.getData().getNickName());
                                    intent.putExtra("sex", result.getData().getSex());
                                    intent.putExtra("imgurl", result.getData().getHeadImgUrl());
                                    intent.putExtra("thirdToken", thirdToken);
                                    startActivity(intent);
                                    break;

                                case -1://-1，用户已被禁用；
                                    ToastUtil.showToast(LoginActivity.this, "用户已被禁用");
                                    break;
                            }
                        } else {
                            ToastUtil.showToast(LoginActivity.this, "登录失败");
                        }
                        finish();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        finish();
                    }
                });
    }

    /**
     * QQ登录成功（已经绑定手机和完善信息）
     *
     * @param result
     */
    private void loginQQSuccess(ObjectResult<LoginRegisterResult> result) {
        if (result.getData().getIsRegister() == 1) {
            boolean success = false;
            if (result.getResultCode() == com.sk.weichat.volley.Result.CODE_SUCCESS) {
                success = LoginHelper.setLoginUser(mContext, coreManager, "888", result.getData().getPassword(), result);// 设置登录用户信息
            }
            if (success) {
                PreferenceUtils.putBoolean(this, Constants.LOGIN_CONFLICT, false);// 重置登录冲突记录
                LoginRegisterResult.Settings settings = result.getData().getSettings();
                MyApplication.getInstance().initPayPassword(result.getData().getUserId(), result.getData().getPayPassword());
                PrivacySettingHelper.setPrivacySettings(LoginActivity.this, settings);
                // 登录成功
                LoginRegisterResult.Login login = result.getData().getLogin();
                if (login != null && login.getSerial() != null && login.getSerial().equals(DeviceInfoUtil.getDeviceId(mContext))
                        && mOldLoginStatus != LoginHelper.STATUS_USER_NO_UPDATE && mOldLoginStatus != LoginHelper.STATUS_NO_USER) {
                    // 如果Token没变，上次更新也是完整更新，那么直接进入Main程序
                    // 其他的登录地方都需进入DataDownloadActivity，在DataDownloadActivity里发送此广播
                    LoginHelper.broadcastLogin(LoginActivity.this);
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {

                    //使用自有账号登录时，可以这样统计：
                    MobclickAgent.onProfileSignIn(coreManager.getSelf().getUserId());
                    // 否则，进入数据下载界面
                    startActivity(new Intent(LoginActivity.this, DataDownloadActivity.class));

                }
                finish();
            } else {
                // 登录失败
                String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                ToastUtil.showToast(mContext, message);
            }
        }
    }

    private void goToWeb(String title, String url) {
        Intent intent = new Intent(LoginActivity.this, WebAgreementActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            startSmsLogin();
        }
        return super.onKeyDown(keyCode, event);
    }
}
